package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.demo.entity.User;
import org.example.demo.mapper.UserMapper;
import org.example.demo.service.MailService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.JWTUtils;
import org.example.demo.util.ReturnMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mail")
public class MailResetController {

    @Autowired
    private MailService mailService;

    @Autowired
    private UserService userService;

    /**
     * 获取重置密码的验证码
     */
    @GetMapping("/getCode")
    public AjaxResult getCode(@RequestParam String userEmail){
        return mailService.getCode(userEmail);
    }

    /**
     * 检查重置密码的验证码是否正确
     */
    @GetMapping("/checkCode")
    public AjaxResult checkCode(@RequestParam String userEmail,@RequestParam String code){
        return mailService.checkCode(userEmail,code);
    }

    /**
     * 检查重置密码的验证码是否正确
     */
    @GetMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestParam String userEmail,@RequestParam String pwd){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> selectUser = userService.list(queryWrapper.lambda()
                .eq(User::getEmail, userEmail));
        if (selectUser.isEmpty()){
            // 用户不存在
            return AjaxResult.error(HttpStatus.NOT_FOUND.value(),"用户不存在");
        }
        User user = selectUser.get(0);
        user.setPwd(pwd);
        userService.updateById(user);
        return AjaxResult.success();
    }
}